const router = require('koa-router')();
const listOrders = require('../../app/mws/orders/ListOrders');
const listOrderItems = require('../../app/mws/orders/ListOrderItems');
const getOrder = require('../../app/mws/orders/GetOrder');

router.prefix('/api/v1/orders');
router.get('/', function (ctx, next) {
  ctx.body = 'this is a listOrders response!'
});

router.get('/listing', async (ctx, next) => {
  const sellerId = ctx.headers.sellerid;
  const mwsAuthToken = ctx.headers.mwsauthtoken;
  const marketplaceid = ctx.query.marketplaceid;

  try {
    let json = await listOrders.listOrdersAll(sellerId, mwsAuthToken, [marketplaceid]);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

router.get('/listing/:orderid', async (ctx, next) => {
  const sellerId = ctx.headers.sellerid;
  const mwsAuthToken = ctx.headers.mwsauthtoken;
  const orderid = ctx.params.orderid;

  try {
    let json = await listOrderItems.listOrderItems(sellerId, mwsAuthToken, orderid);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

router.get('/:orderIdList', async (ctx, next) => {
  const sellerId = ctx.headers.sellerid;
  const mwsAuthToken = ctx.headers.mwsauthtoken;
  const orderIdList = ctx.params.orderIdList.split(',').map(item => item.trim());

  try {
    let json = await getOrder.getOrder(sellerId, mwsAuthToken, orderIdList);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

module.exports = router;